package com.vegas.netspider.memdb;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.h2.jdbcx.JdbcConnectionPool;
import org.springframework.core.io.Resource;

public class DbOperator {

	private JdbcConnectionPool pool;
	private String tablesScript;
	private List<MemDBCloseListener> listeners;
	
	public void setScript(Resource res) throws IOException{
		FileReader fr = new FileReader(res.getFile());
		BufferedReader br = new BufferedReader(fr);
		String line = null;
		StringBuffer buffer = new StringBuffer();
		while((line=br.readLine())!=null){
			buffer.append(line);
		}
		tablesScript = buffer.toString();
	}
	
	public void init() throws ClassNotFoundException, SQLException{
		String dbUrl = "jdbc:h2:mem:vegas";
		
		Class.forName("org.h2.Driver");
	
		pool = JdbcConnectionPool.create(dbUrl, "robet", "hellogoogleposter");
		pool.setMaxConnections(30);
		
		this.createTables();
	}
	
	public void close(){
		if(this.listeners==null){
			return;
		}
		for(MemDBCloseListener l:listeners){
			l.onClose();
		}
	}
	
	public void registListener(MemDBCloseListener l){
		if(this.listeners==null){
			this.listeners = new ArrayList<MemDBCloseListener>();
		}
		
		this.listeners.add(l);
	}
	
	public Connection getConnection() throws SQLException{
		return pool.getConnection();
	}
	
	private void createTables() throws SQLException{
		Connection conn = this.getConnection();
		Statement stat = conn.createStatement();
		stat.execute(tablesScript);
		stat.close();
		conn.close();
	}
	
	public DataSource getDataSource(){
		return pool;
	}
	
}
